package cn.tedu.service;

import cn.tedu.pojo.Car;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@Component
public class CarServiceImpl implements CarService{

    @Override
    public Car get() {
        Car c =new Car();
        c.setName("奥迪A6L");
        c.setColor("黑色");
        c.setPrice(458888.05);
        return c;
    }

    @Override
    public void add(Car c) {
        PreparedStatement ps = null;
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydemo1", "root", "root");
            String sql = "insert into Car(name ,color,price) values(?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, c.getName());
            ps.setString(2, c.getColor());
            ps.setDouble(3, c.getPrice());
            ps.executeUpdate();

            System.out.println("入库成功~~~");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } finally {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        System.out.println(c);
    }

    @Override
    public void update(Car c) {
        //利用jdbc修改数据
        PreparedStatement ps = null;
        Connection conn = null;
        try {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydemo1", "root", "root");
            String sql = "update car set price=? where name=?";
            ps = conn.prepareStatement(sql);
            ps.setDouble(1, c.getPrice());
            ps.setString(2, c.getName());
            ps.executeUpdate();

            System.out.println("修改成功~~~");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } finally {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        System.out.println(c);
    }
}
